package com.sx.zongzhi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.KeyPunishAdapter;
import com.sx.zongzhi.bean.KeyPunishBean;
import com.sx.zongzhi.bean.KeyPunishSearchBean;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.OrganizingBean;
import com.sx.zongzhi.bean.UserBean;
import com.sx.zongzhi.presenter.KeyPunishPest;
import com.sx.zongzhi.utils.AppConstants;
import com.sx.zongzhi.utils.Global;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.IKeyPunishView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

/**
 * 重点地区整治
 */
public class KeyPunishActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener
,IKeyPunishView{

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.imvAdd)
    ImageView imvAdd;
    @BindView(R.id.tv_Total)
    TextView tv_Total;

    private KeyPunishPest punishPest;
    private KeyPunishAdapter punishAdapter;
    private List<KeyPunishBean.RowsBean> keyPunishList=new ArrayList<>() ;
    /**筛选的网格对象*/
    private OrganizingBean oBean;
    private String orgId="";
    private int currentPage=1;
    private Disposable disposable;
    private KeyPunishBean.PermissionBean userPermission;
    private boolean isCurrentGrid = false;
    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_household);
        ButterKnife.bind(this);
        setTitleName(R.string.key_punish);
        setRightImage(R.mipmap.icon_nav_search);
        initView();
        onRefresh();
    }

    private void initView() {
        punishPest=new KeyPunishPest(this);
        IDataStorage dataStorage=DataStorageFactory.getInstance(
                getApplicationContext(),
                DataStorageFactory.TYPE_DATABASE);
        UserBean userBean=dataStorage.load(UserBean.class,getPackageName());
        orgId=userBean.getOrg().getId();
        imvAdd.setVisibility(View.GONE);
        if ("片组片格".equals(userBean.getOrg().getOrgLevel().getDisplayName())){//只有网格员可以添加
            isCurrentGrid = true;
        }else {
            setRightImage2(R.mipmap.icon_nav_position);
        }
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setColorSchemeResources(AppConstants.colors);
            swipeRefreshLayout.setOnRefreshListener(this);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        punishAdapter = new KeyPunishAdapter(this,R.layout.item_key_punish_list,keyPunishList);
        punishAdapter.setEmptyView(View.inflate(this,R.layout.load_error_view,null));
        recyclerView.setAdapter(punishAdapter);
        punishAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                currentPage++;
                loadDataList();
            }
        },recyclerView);
        punishAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(KeyPunishActivity.this, KeyPunishDetailActivity.class)
                        .putExtra("keyPunishId",keyPunishList.get(position).getId())
                        .putExtra("orgId",orgId)
                .putExtra("userPermission",userPermission));
            }
        });

        //订阅筛选组织机构
        disposable= MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent bean) throws Exception {
                        if ("KeyPunishActivity".equals(bean.getRequest())) {
                            if (bean.getType()==0) {
                                oBean = (OrganizingBean) bean.getMsg();
                                if (oBean != null) {
                                    currentPage=1;
                                    orgId = oBean.getId();
                                    loadDataList();
                                    if (oBean.isGrid() && userPermission != null && userPermission.isAddSocialSecurity()){
                                        imvAdd.setVisibility(View.VISIBLE);
                                    }else {
                                        imvAdd.setVisibility(View.GONE);
                                    }
                                }
                            }else if (bean.getType()==2){//查询
                                KeyPunishSearchBean  searchBean= (KeyPunishSearchBean) bean.getMsg();
                                punishPest.getKeyPunishList("searchSocialSecurity.action",orgId,searchBean,currentPage,10);
                            }else if (bean.getType()==1){//增删改
                                onRefresh();
                            }
                        }
                    }
                });
    }

    @OnClick({R.id.imv_Right,R.id.imvAdd,R.id.imv_Right2})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.imv_Right:
                startActivity(new Intent(KeyPunishActivity.this,KeyPunishSearchActivity.class));
                break;
            case R.id.imv_Right2://位置筛选
                startActivity(new Intent(this,OrganizingActivity.class).
                        putExtra(Global.ACTIVITY_FRAGMENT,"KeyPunishActivity"));
                break;
            case R.id.imvAdd:
                startActivity(new Intent(KeyPunishActivity.this,KeyPunishEditActivity.class)
                        .putExtra("orgId",orgId));
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (disposable!=null){
            disposable.dispose();
        }
        super.onDestroy();
    }

    @Override
    public void onRefresh() {
        currentPage=1;
        loadDataList();
    }

    public void loadDataList() {
        punishPest.getKeyPunishList("getSocialSecurityList.action",orgId,null,currentPage,10);
    }
    @Override
    public void getKeyPunishList(KeyPunishBean punishBean) {
        swipeRefreshLayout.setRefreshing(false);
        if (punishBean.getPermission() != null && userPermission == null){
            userPermission = punishBean.getPermission();
            if (isCurrentGrid && userPermission.isAddSocialSecurity()){
                imvAdd.setVisibility(View.VISIBLE);
            }
        }
        if (currentPage==1){
            keyPunishList.clear();
            punishAdapter.setNewData(keyPunishList);
        }
        if (punishBean.getRows()!=null) {
            keyPunishList.addAll(punishBean.getRows());
        }
        if (keyPunishList.size()>=punishBean.getRecords()) {
            punishAdapter.loadMoreEnd();
        }else {
            punishAdapter.loadMoreComplete();
        }
        punishAdapter.notifyDataSetChanged();
        tv_Total.setText("共"+punishBean.getTotal()+"条数据");
    }

    @Override
    public void showError(String message) {
        swipeRefreshLayout.setRefreshing(false);
        ToastUtils.showToast(this,message);
    }
}
